//实现发布订阅

const { default: axios } = require("axios")

class EventEmitter {
    constructor(){
        this.events = {}
    }

    // 实现订阅
    on(name,fn){
        if(this.events[name]){
            this.events[name].push(fn)
        } else {
            this.events[name] = [fn]
        }
    }

    // 删除订阅
    off(name,fn){
        if(!this.events[name]) return
        this.events[name] = this.events[name].filter(item=>{return item !== fn})
    }

    // 只执行一次订阅事件
    once(name, fn){
        function f(){
            fn()
            this.off(name, f)
        }
       this.on(name, f)
    }

    // 触发事件
    emit(name,...rest){
        this.events[name] && this.events[name].forEach(fn => fn.apply(this,...rest))
    }
}

//测试
const eventBus = new EventEmitter()
const task1 = () => { console.log('task1') }
const task2 = () => { console.log('task2') }

eventBus.on('task', task1)
eventBus.on('task', task2)
// eventBus.off('task',task1)

setTimeout(()=>{
    eventBus.emit('task')
}, 1000)

//异步控制并发数
function limitRequest(urls = [], limit = 3){
    return new Promise((resolve,reject)=>{
        const len = urls.length
        let count = 0

        while(limit > 0){
            start()
            limit -=1
        }

        function start(){
            const url = urls.unshift() // 从数组中拿取第一个任务
            if(url){
                axios.post(url).then(res => {
                    //todo
                }).catch(err => {
                    //todo
                }).finally(()=>{
                    if(count === len - 1){
                        //最后一个任务完成
                        resolve()
                    } else {
                        //完成之后，启动下一个任务
                        count ++
                        start()
                    }
                })
            }
        }

    })
}

//测试
// limitRequest(['http://xxa', 'http://xxb', 'http://xxc', 'http://xxd', 'http://xxe'])